<template>
	<div class="equipBasic">
		<el-row>
			<el-button size="mini" type="primary" @click="viewQrCode" style="float:right;margin-right:5px;">查看二维码</el-button>
		</el-row>
		<div class="form">
			<el-form label-width="120px" :inline="false" class="demo-form-inline " :model="form" :rules="rules" ref="instrumentAddForm">
				<el-row>
					<el-col :span="12">
						<el-form-item label="名称" prop="ename">
							<el-input size="mini" v-model="form.ename" placeholder="请输入内容" disabled></el-input>
						</el-form-item>
					</el-col>
					<el-col :span="12">
						<el-form-item label="类别:" prop="equipmentType">
							<el-cascader disabled size="mini" clearable expand-trigger="hover" :show-all-levels="false" :options="equipmentTypeData"
							 :props="props" v-model="equipmentType" filterable>
							</el-cascader>
						</el-form-item>
						<!--<el-form-item label="编号:" prop="code">
                  <el-input size="mini" disabled v-model="form.code" placeholder="请输入内容"></el-input>
            		</el-form-item>-->
					</el-col>
				</el-row>
				<el-row>
					<el-col :span="12">
						<!--{{equipmentType}}-->
						<el-form-item label="规格型号:" prop="model">
							<el-input disabled size="mini" v-model="form.model" placeholder="请输入内容"></el-input>
						</el-form-item>
					</el-col>
					<el-col :span="12">
						<el-form-item label="设备编号:" prop="enterCode">
							<el-input size="mini" v-model="form.enterCode" placeholder="请输入内容" disabled></el-input>
						</el-form-item>

						<!--<el-form-item label="使用前检查：" prop="doUseCheck">
                  <el-select v-model="form.doUseCheck" placeholder="请选择" size="mini">
	                  <el-option label="是" value="true"></el-option>
	                  <el-option label="否" value="false"></el-option>
	                </el-select>
            		</el-form-item>-->
					</el-col>
				</el-row>
        <el-row>
          <el-col :span="12">
          	<el-form-item :label="stationName" prop="offices">
          		<el-select v-model="form.offices" placeholder="请选择" size="mini"  disabled>
          			<el-option label="全部" value="ALL"></el-option>
                <el-option v-for="item in stationList" :key="item.id" :label="item.name" :value="item.id">
          			</el-option>
          		</el-select>
          	</el-form-item>
          </el-col>
        	<el-col :span="12">
        		<el-form-item label="分组:" prop="grouping">
        			<el-select disabled v-model="form.grouping" placeholder="请选择" size="mini">
        				<el-option v-for="item in groupSelect.itemList" :key="item.code" :label="item.name" :value="item.code">
        				</el-option>
        			</el-select>
        		</el-form-item>
        	</el-col>
        </el-row>
        <el-row>
          <el-col :span="12">
            <el-form-item label="负责人:" prop="custodian">
            	<el-select v-model="form.custodian" placeholder="请选择" size="mini" filterable disabled>
            		<el-option v-for="item in userData" :key="item.account" :label="item.name" :value="item.account" >
            		</el-option>
            	</el-select>
            </el-form-item>
          </el-col>
          <el-col :span="12">
          	<el-form-item label="购买日期:" prop="purchaseDate">
          		<el-date-picker disabled v-model="form.purchaseDate" type="date" size="mini" style="width:100%" placeholder="选择日期" format="yyyy-MM-dd"
          		 value-format="yyyy-MM-dd">
          		</el-date-picker>
          	</el-form-item>
          </el-col>
        </el-row>
				<el-row>
					<el-col :span="12">
						<el-form-item label="出厂编号:" prop="factory">
							<el-input disabled size="mini" v-model="form.factory" placeholder="请输入内容"></el-input>
						</el-form-item>
					</el-col>
					<el-col :span="12">
						<el-form-item label="位置:" prop="location">
							<el-input disabled size="mini" v-model="form.location" placeholder="请输入内容"></el-input>
						</el-form-item>
					</el-col>
				</el-row>
        

				<el-row>

					<el-col :span="12">
						<el-form-item label="制造商:" prop="manufacturer">
							<el-input size="mini" disabled v-model="form.manufacturer" placeholder="请输入内容"></el-input>
						</el-form-item>
						<!--<el-form-item label="价格（万元）:" prop="price">
						  		<el-input size="mini" v-model.number="form.price" placeholder="请输入内容"></el-input>
            		</el-form-item>-->
					</el-col>
          <el-col :span="12">
          	<el-form-item label="供应商:" prop="supplier">
          		<el-select disabled v-model="form.supplier" placeholder="请选择" size="mini">
          			<el-option v-for="item in supplierData" :key="item.id" :label="item.name" :value="item.id" >
          			</el-option>
          		</el-select>
          	</el-form-item>


          </el-col>
				</el-row>
				<el-row>

					<el-col :span="12">
						<el-form-item label="校准日期:" prop="executeDate">
							<el-date-picker disabled v-model="form.executeDate" type="date" size="mini" style="width:100%" placeholder="选择日期" format="yyyy-MM-dd"
							 value-format="yyyy-MM-dd">
							</el-date-picker>
						</el-form-item>
					</el-col>
          <el-col :span="12">
          	<el-form-item label="有效期:" prop="expiryDate">
          		<el-date-picker disabled v-model="form.expiryDate" type="date" size="mini" style="width:100%" placeholder="选择日期" format="yyyy-MM-dd"
          		 value-format="yyyy-MM-dd">
          		</el-date-picker>
          	</el-form-item>
          </el-col>
				</el-row>
			</el-form>
		</div>
		<div class="table">
			<div style="height:30px;line-height:30px;">
				承担的能力参数
			</div>
			<el-table :data="abilityTableDate" style="width: 100%;height:calc(100% - 45px)" class="tableCon" size="mini" key="abilityTableDate"
				ref="standardTable">
				<el-table-column label="序号" min-width="50px">
					<template slot-scope="scope">
						{{scope.$index+1}}
					</template>
				</el-table-column>
				<el-table-column property="detectabilityName" label="能力参数" min-width="120px">
				</el-table-column>
				<el-table-column property="group" label="检测项目分组" min-width="80px" :formatter="formatterGrop" overflow-tooltip>
				</el-table-column>
				<el-table-column property="methodName" show-overflow-tooltip label="方法" min-width="120px" overflow-tooltip>
				</el-table-column>
				<el-table-column property="isMain" show-overflow-tooltip label="主仪器" min-width="80px" >
					<template slot-scope="scope">
						{{scope.row.isMain == true?'是':'否'}}
					</template>
				</el-table-column>
				<el-table-column property="isMain" show-overflow-tooltip label="辅助仪器" min-width="80px">
					<template slot-scope="scope">
						{{scope.row.isMain == false ?'是':'否'}}
					</template>
				</el-table-column>

			</el-table>

		</div>
		<div class="codeDiv topDistance" v-if="showQrCode">
			<div class="codeTop">
				<span class="codeTitle">二维码</span>
				<span class="codeClose" @click="() => (showQrCode = false)">
				<i class="el-icon-close"></i>
				</span>
			</div>
			<div class="codeContent" ref="codeImg">
				<canvas
				id="canvas"
				ref="codeImg1"
				width="280"
				height="420"
				></canvas>
				<div class="QRCode" style="display: none" ref="qrCodeUrl"></div>
			</div>
			<div class="codeBtn">
				<el-button
				slot="reference"
				icon="el-icon-printer"
				class="el-button--plain"
				size="mini"
				@click="printCode"
				>打印</el-button
				>
				<el-button
				class="el-button--plain"
				size="mini"
				icon="el-icon-download"
				@click="downloadQrCode"
				>下载</el-button
				>
			</div>
		</div>
		<div
			style="
			width: 280px;
			height: 420px;
			position: absolute;
			z-index: -999;
			left: 25%;
			top: 10%;
			"
		>
			<img
			ref="canvasImg"
			style="
				width: 280px;
				height: 420px;
				position: absolute;
				left: 25%;
				top: 10%;
				border-radius: 10px;
				border: 1px solid rgb(116, 116, 116);
			"
			:src="canvasUrl"
			fit="scale-down"
			/>
		</div>
	</div>
</template>

<script>
	import { mapState } from 'vuex'
	import QRCode from "qrcodejs2"

	export default {
		props: {
			detailData: Object
		},
		data() {
			return {
				qrUrl: "",
				showQrCode:false,
       			canvasUrl:null,
      			backgroundImgUrl: require("@/assets/img/logo.png"),
				form: {
					id: '',
					ename: "",
					enterCode: "",
					equipmentType: '',
					doUseCheck: "",
					model: "",
					factory: "",
					factoryDate: "",
					purchaseDate: "",
					price: "",
					location: "",
					supplier: "",
					manufacturer: "",
					grouping: '',
					status: "2",
					sort: "",
          custodian:'',
          custodianName:'',
				},
				rules: {
					ename: [{
						required: true,
						type: 'string',
						message: '请填写名称',
						trigger: 'blur'
					},],
					grouping: [{
						required: true,
						type: 'string',
						message: '请选择分组',
						trigger: 'blur'
					},],
          offices:[{
            required: true,
          	message: '请选择',
          	trigger: 'blur',
          }],
					manufacturer: [{
						required: true,
						type: 'string',
						message: '填写制造商',
						trigger: 'blur'
					},],
					model: [{
						required: true,
						type: 'string',
						message: '请填写规格型号',
						trigger: 'blur'
					},],
					enterCode: [{
						required: true,
						type: 'string',
						message: '请选择',
						trigger: 'blur'
					},],
					equipmentType: [{
						required: true,
						type: 'string',
						message: '请选择',
						trigger: 'blur'
					}],
          custodian: [{
          	required: true,
          	type: 'string',
          	message: '请选择仪器负责人',
          	trigger: 'change'
          }]
				},
				equipmentType: [],
				supplierData: [],
				equipmentTypeData: [],
				props: {
					value: 'id',
					label: 'name'
				},
				page: 1,
				abilityTableDate: [{
					typeofAbilityID: '10289001',
					typeofAbilityName: '有机',
					abilityStatus: '1',
					sampleTypeID: '10001',
					sampleTypeName: '水',
					remark: '备注',
					abilityID: '10011',
					abilityName: '氨氮-纳氏试剂法',
					abilityCode: '10011',
					abilityMethod: '纳氏试剂法',
					reportName: '氨氮',
					mainEquipID: '10001',
					mainEquipName: '主仪器',
					frontEquipID: '100001',
					frontEquipName: '副仪器',
					banbenhao: 'v1'
				}],
				equipmentList: [],
        stationName:"厂站",
        stationList:[],
        userData:[],
			}
		},
		computed: {
			...mapState(['enableStatus1', 'groupSelect', 'yesorno', 'enableStatus', 'mainEquipType', 'dataSelect', 'unitTableDate', 'ruleSelect'])
		},
		created() {
			this.getQrUrl();
       this.getStaion()
			// this.getEquipmentInfo()
			this.$store.dispatch('dogetDictionary')
		},
		mounted() {
			this.form.id = this.detailData.id
			this.form.ename = this.detailData.ename
			this.form.enterCode = this.detailData.enterCode
			this.form.doUseCheck = this.detailData.doUseCheck + ''
			this.form.model = this.detailData.model
			this.form.factory = this.detailData.factory
			this.form.factoryDate = this.detailData.factoryDate
			this.form.purchaseDate = this.detailData.purchaseDate
			this.form.price = this.detailData.price
			this.form.location = this.detailData.location
			this.form.supplier = this.detailData.supplier
			this.form.manufacturer = this.detailData.manufacturer
			this.form.grouping = this.detailData.grouping
      this.form.executeDate = this.detailData.executeDate
      this.form.expiryDate = this.detailData.expiryDate
      if(this.detailData.offices){
        this.form.offices = this.detailData.offices
      }else{
        this.form.offices = ''
      }
      console.log(this.form)
			this.init()

		},
		methods: {
			getQrUrl() {
				this.$http({
					apiUrl: 'resource/getQrUrl.htm',
					method: 'get',
				}).then(res => {
					if (res.code == 0) {
						this.qrUrl = res.data;
					}
				})
			},
			// 查看二维码
			async viewQrCode() {
				this.showQrCode = true;
				this.$nextTick(() => {
					new QRCode(this.$refs.qrCodeUrl, {
					text: this.qrUrl + "/qrCode.html?id=" + this.form.id, // 需要转换为二维码的内容
					width: 250,
					height: 250,
					colorDark: "#000000",
					colorLight: "#ffffff",
					correctLevel: QRCode.CorrectLevel.L,
					});
				});
				setTimeout(() => {
					let el = document.querySelectorAll(".QRCode img");
					this.qrCodeUrl = el[0].src;
					this.loadQrCode();
				}, 100);
			},
			loadQrCode() {
				let pointName = this.form.ename;
				const canvas = document.getElementById("canvas");
				const ctx = canvas.getContext("2d");
				let imgLog = new Image();
				let imgCode = new Image();
				imgLog.src = this.backgroundImgUrl;
				imgCode.src = this.qrCodeUrl;
				ctx.fillStyle = "rgb(40, 26, 113)";
				ctx.fillRect(0, 340, 280, 80);
				ctx.textAlign = "center";
				ctx.strokeStyle = "white";
				ctx.font = "normal normal 200 14px Microsoft YaHei";
				let strlength1 = ctx.measureText(pointName).width;
				ctx.font = "normal normal 200 16px Microsoft YaHei";
				let strlength2 = ctx.measureText(pointName).width;
				ctx.font = "normal normal 200 24px Microsoft YaHei";
				let strlength3 = ctx.measureText(pointName).width;
				if (strlength1 > 520) {
					ctx.font = "normal normal 200 14px Microsoft YaHei";
					this.canvasTextAutoLine(pointName, ctx, 140, 365, 20, canvas);
				} else if (strlength2 > 520 && strlength1 < 520) {
					ctx.font = "normal normal 200 14px Microsoft YaHei";
					this.canvasTextAutoLine(pointName, ctx, 140, 375, 20, canvas);
				} else if (strlength2 > 260) {
					ctx.font = "normal normal 200 16px Microsoft YaHei";
					this.canvasTextAutoLine(pointName, ctx, 140, 375, 20, canvas);
				} else if (strlength3 > 260 && strlength2 < 260) {
					ctx.font = "normal normal 200 16px Microsoft YaHei";
					this.canvasTextAutoLine(pointName, ctx, 140, 385, 20, canvas);
				} else {
					ctx.font = "normal normal 200 24px Microsoft YaHei";
					this.canvasTextAutoLine(pointName, ctx, 140, 385, 20, canvas);
				}
				let imageData = ctx.getImageData(0, 0, 280, 420);
				for (let i = 0; i < imageData.data.length; i += 4) {
					// 当该像素是透明的,则设置成白色
					if (imageData.data[i + 3] == 0) {
					imageData.data[i] = 255;
					imageData.data[i + 1] = 255;
					imageData.data[i + 2] = 255;
					imageData.data[i + 3] = 255;
					}
				}
				ctx.putImageData(imageData, 0, 0);
				let url = canvas.toDataURL("image/jpg");
				this.canvasUrl = url;
				imgLog.onload = () => {
					ctx.drawImage(imgLog, 20, 10, 200, 50);
					let url = canvas.toDataURL("image/jpg");
					this.canvasUrl = url;
				};
				imgCode.onload = () => {
					ctx.drawImage(imgCode, 20, 80, 240, 240);
					let url = canvas.toDataURL("image/jpg");
					this.canvasUrl = url;
				};
			},
			printCode() {
		    	this.$print(this.$refs.canvasImg);
			},
			/*
				str:要绘制的字符串
				ctx:canvas对象
				initX:绘制字符串起始x坐标
				initY:绘制字符串起始y坐标
				lineHeight:字行高，自己定义个值即可
			*/
			canvasTextAutoLine(str, ctx, initX, initY, lineHeight, c) {
				let lineWidth = 0;
				let canvasWidth = c.width - 20;
				let lastSubStrIndex = 0;
				for (let i = 0; i < str.length; i++) {
					lineWidth += ctx.measureText(str[i]).width;
					if (lineWidth > canvasWidth) {
					//减去initX,防止边界出现的问题
					ctx.strokeText(
						str.substring(lastSubStrIndex, i),
						initX,
						initY,
						canvasWidth
					);
					initY += lineHeight;
					lineWidth = 0;
					lastSubStrIndex = i;
					}
					if (i == str.length - 1) {
					ctx.strokeText(
						str.substring(lastSubStrIndex, i + 1),
						initX,
						initY,
						canvasWidth
					);
					}
				}
			},
			downloadQrCode() {
				let pointName = this.form.ename;
				const canvas = document.createElement("canvas");
				canvas.width = "560";
				canvas.height = "840";
				const ctx = canvas.getContext("2d");
				ctx.fillStyle = "rgb(40, 26, 113)";
				ctx.fillRect(0, 680, 560, 160);
				ctx.textAlign = "center";
				ctx.strokeStyle = "white";
				ctx.font = "normal normal 200 28px Microsoft YaHei";
				let strlength1 = ctx.measureText(pointName).width;
				ctx.font = "normal normal 200 32px Microsoft YaHei";
				let strlength2 = ctx.measureText(pointName).width;
				ctx.font = "normal normal 200 40px Microsoft YaHei";
				let strlength3 = ctx.measureText(pointName).width;
				if (strlength1 > 1080) {
					ctx.font = "normal normal 200 28px Microsoft YaHei";
					this.canvasTextAutoLine(pointName, ctx, 280, 730, 40, canvas);
				} else if (strlength2 > 1080 && strlength1 < 1080) {
					ctx.font = "normal normal 200 28px Microsoft YaHei";
					this.canvasTextAutoLine(pointName, ctx, 280, 750, 40, canvas);
				} else if (strlength2 > 520) {
					ctx.font = "normal normal 200 32px Microsoft YaHei";
					this.canvasTextAutoLine(pointName, ctx, 280, 750, 40, canvas);
				} else if (strlength3 > 520 && strlength2 < 520) {
					ctx.font = "normal normal 200 32px Microsoft YaHei";
					this.canvasTextAutoLine(pointName, ctx, 280, 770, 40, canvas);
				} else {
					ctx.font = "normal normal 200 40px Microsoft YaHei";
					this.canvasTextAutoLine(pointName, ctx, 280, 770, 40, canvas);
				}
				let imageData = ctx.getImageData(0, 0, 560, 840);
				for (let i = 0; i < imageData.data.length; i += 4) {
					// 当该像素是透明的,则设置成白色
					if (imageData.data[i + 3] == 0) {
					imageData.data[i] = 255;
					imageData.data[i + 1] = 255;
					imageData.data[i + 2] = 255;
					imageData.data[i + 3] = 255;
					}
				}
				ctx.putImageData(imageData, 0, 0);
				let p1 = new Promise((resolve, reject) => {
					let imgLog = new Image();
					imgLog.src = this.backgroundImgUrl;
					imgLog.onload = () => {
					ctx.drawImage(imgLog, 40, 20, 400, 100);
					resolve(true);
					};
				});
				let p2 = new Promise((resolve, reject) => {
					let imgCode = new Image();
					imgCode.src = this.qrCodeUrl;
					imgCode.onload = () => {
					ctx.drawImage(imgCode, 40, 160, 480, 480);
					resolve(true);
					};
				});
				Promise.all([p1, p2]).then((res) => {
					let url = canvas.toDataURL("image/jpg");
					this.canvasUrl = url;
					let a = document.createElement("a");
					let event = new MouseEvent("click");
					a.download = pointName + "-二维码.png";
					a.href = url;
					a.dispatchEvent(event);
					})
					.catch((e) => {
					console.log(e);
				});
			},
      getStaion(){
          this.stationName = this.util.getStationName()
          this.stationList = this.util.getStationList()

      },
			formatterGrop(row, column, cellValue, index) {
				return this.util.codeChangeName({ cellValue: cellValue, list: this.groupSelect.itemList })
			},
			getEquipmentInfo() {
				this.$http({
					apiUrl: 'resource/getEquipmentInfo.htm',
					method: 'post',
					params: { name: '' },
				}).then(res => {
					if (res.code == 0) {
						//					console.log(res)
						this.equipmentList = res.data
					}
				})
			},
			init() {
				this.$http({
					apiUrl: 'resource/readEquipment.htm',
					method: 'post',
					params: {
						id: this.detailData.id
					},
					isJson: false,
				}).then(res => {
					if (res.code == 0) {
            this.form = res.data;
            if(!this.form.offices){
              this.form.offices = ""
            }
						this.abilityTableDate = res.data.detecEquipBeanList
					}
				})
				this.$http({
					apiUrl: 'resource/readSupplierComboList.htm',
					method: 'post',
					params: '',
				}).then(res => {
					if (res.code == 0) {
						this.supplierData = res.data
					}
				})
				this.$http({
					apiUrl: 'resource/readMainEquipTypeList.htm',
					method: 'post',
					params: '',
				}).then(res => {
					if (res.code == 0) {
						this.equipmentTypeData = res.data
						//有值回显
						if (this.detailData.equipmentType) {
							res.data.forEach(i => {
								if (i.id === this.detailData.equipmentType) {
									this.equipmentType.push(i.id)
								} else {
									if (i.children.length > 0) {
										i.children.forEach(k => {
											if (k.id === this.detailData.equipmentType) {
												this.equipmentType.push(i.id)
												this.equipmentType.push(k.id)
											}
										})
									}
								}
							})
						}
					}
				})
        this.$http({
          method: 'post',
          apiUrl: '/resource/readEmployeeByLab.htm',
          params: { name: '' },
          isJson: true,
        }).then(res => {
          if (res.code === 0) {
            this.userData = res.data;
          }

        })
      },
			close() {
				this.$parent.addShow = false
			},
			tabDivMinHeight() {
				return (window.innerHeight - 560)
			},
			submit() {
				if (this.equipmentType.length === 1) {
					this.form.equipmentType = this.equipmentType[0]
				} else {
					this.form.equipmentType = this.equipmentType[this.equipmentType.length - 1]
				}
				this.$refs.instrumentAddForm.validate((valid) => {
					if (valid) {
						this.$http({
							apiUrl: 'resource/updateEquipment.htm',
							method: 'post',
							params: this.form,
						}).then(res => {
							if (res.code == 0) {
								this.$parent.close()
							}
						})
					} else {
						return false
					}
				})
			},
			handleSizeChange() { },
			handleCurrentChange() { },
		}
	}

</script>

<style lang="less"scoped>
	.el-cascader {
		width: 100%;
	}

	.el-input-number--mini {
		width: 100%;
	}

	.el-select {
		width: 100%;
	}
	.codeContent {
		width: 100%;
		text-align: center;
		display: flex;
		justify-content: center;
		align-items: center;
	}
	.codeDiv {
		position: absolute;
		width: 300px;
		height: 510px;
		background-color: #ffffff;
		border: 1px solid #e4e4e4;
		border-radius: 4px;
		top: 120px;
		right: 10px;
		z-index: 999;
		.codeTop {
			display: flex;
			flex-flow: wrap nowrap;
			justify-content: space-between;
			.codeClose {
			padding: 5px 15px;
			cursor: pointer;
			}
		}
		.codeTitle {
			text-align: left;
			padding: 5px 15px;
		}
		.codeBtn {
			padding: 15px;
		}
	}
	.topDistance {
		top: 30px;
	}
	#canvas {
		border: 1px solid rgb(116, 116, 116);
		border-radius: 10px;
		letter-spacing: 2px;
		background-color: #fff;
	}
</style>
<style>
	.equipBasic {
		position: relative;
        background-color: #ffffff;
		height: 100%;
	}
	.equipBasic .form{
		height:320px;
	}
	.equipBasic .table{
		height: calc(100% - 320px);
		clear:both;
	}

	.equipBasic .el-form-item {
		margin-bottom: 6px;
	}
</style>
